﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PeiYue.Common.Helper;
using PeiYue.Common.HttpContextUser;
using PeiYue.IServices.Purchase;
using PeiYue.IServices.Store;
using PeiYue.Model;
using PeiYue.Model.Dto.Purchase;
using PeiYue.Model.ERPModels;
using PeiYue.Model.Models.Purchase;
using PeiYue.Model.Models.Store;
using StackExchange.Redis;

namespace PeiYue.Api.Controllers.Purchase
{
    /// <summary>
    /// 供应商分拣
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    //[Authorize(Permissions.Name)]
    [Authorize]
    public class SortingController : ControllerBase
    {
        readonly IPurchaseOrderHeader _purchaseOrderHeader;
        readonly IPurchaseOrderDetail _purchaseOrderDetail;
        readonly ISrmSortingRecord _srmSortingRecord;
        readonly ISupplierServices _supplierServices;
        readonly IReceiptRecordServices _receiptRecordServices;
        readonly IUser _user;
        readonly IMapper _mapper;
        public SortingController(IPurchaseOrderHeader purchaseOrderHeader,
           IPurchaseOrderDetail purchaseOrderDetail,
           ISrmSortingRecord srmSortingRecord,
           ISupplierServices supplierServices,
           IReceiptRecordServices receiptRecordServices,
           IUser user, IMapper mapper)
        {
            _purchaseOrderHeader = purchaseOrderHeader;
            _purchaseOrderDetail = purchaseOrderDetail;
            _srmSortingRecord = srmSortingRecord;
            _supplierServices = supplierServices;
            _receiptRecordServices = receiptRecordServices;
            _user = user;
            this._mapper = mapper;
        }
        /// <summary>
        /// 打印标签 多包裹不同条形码
        /// </summary>
        /// <param name="printData">打印标签参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<string>> PrintPack([FromBody] PrintData printData)
        {
            var printDto = printData.PrintList;
            var data = new MessageModel<string>() { success = false };
            if (printDto == null || printDto.Count == 0)
            {
                data.success = false;
                data.status = 500;
                data.msg = "参数不能为空";
                return data;
            }
            if (printDto.Count(t => t.Qty <= 0) > 0)
            {
                data.success = false;
                data.status = 500;
                data.msg = "发货数量必须大于0";
                return data;
            }
            ErpPurchaseOrderDetail model = null;
            SrmSortingRecordDao dao = null;
            var groupList = printDto.GroupBy(t => t.FID).ToList();
            int packNum = 0;
            int saleId = 0;
            int fId = 0;
            foreach (var group in groupList)
            {
                int i = 0;
                fId = group.Key;
                model = await _purchaseOrderDetail.QueryModel(t => t.fID == fId);
                if (model == null)
                {
                    data.success = false;
                    data.status = 500;
                    data.msg = "无效的参数";
                    return data;
                }
                saleId = string.IsNullOrWhiteSpace(model.SaleId) ? 0 : Convert.ToInt32(model.SaleId);
                ErpPurchaseOrderHeader headerDao = await _purchaseOrderHeader.QueryModel(t => t.OrderId == model.OrderId);
                if (saleId == 0)
                {
                    _srmSortingRecord.DeleteByFId(fId).Wait();
                }
                else
                {
                    _srmSortingRecord.DeleteBySaleId(saleId, headerDao.SupplierCode).Wait();
                }
                //if (_user.Types == 160)
                //{
                //    decimal qty = group.Sum(t => t.Qty);
                //    string upSQL = @"update [供应链].[dbo].采购订单表体  set 报货数=@Qty,收货数=@Qty where fID=@fId  ";
                //    string sql = $@"{upSQL} ;  exec [系统].[dbo].[p日志记录] 'OMS.Wechat',' ','','','{_user.Namec}','自采打码,同步收货数量','','update [供应链].[dbo].采购订单表体  set 报货数={qty},收货数={qty} where fID={fId}  ','','{DateTime.Now}' ";
                //    data.success = await _purchaseOrderDetail.ExecuteCommand(sql, new { qty, fId }) > 0;
                //}
                foreach (var item in group)
                {
                    packNum = i + 1;
                    dao = new SrmSortingRecordDao();
                    dao.FID = item.FID;
                    dao.Qty = item.Qty;
                    dao.Price = model.Price;
                    dao.PackNum = packNum;
                    dao.PackQty = 1;
                    dao.Status = 1;
                    dao.OrderId = model.OrderId;
                    dao.OrderDetailId = saleId;
                    dao.SkuCode = model.SkuCode;
                    dao.SkuId = model.CategoryId.HasValue ? Convert.ToInt64(model.CategoryId) : 0;

                    if (headerDao != null)
                    {
                        dao.SupplierCode = headerDao.SupplierCode;
                        dao.SupplierId = headerDao.SupplierId.Value;
                    }
                    dao.CustomerCode = model.CustomerCode;
                    dao.Flag = 1;
                    dao.CreateUser = _user.ID;
                    dao.CreateTime = DateTime.Now;
                    dao.UpdateUser = _user.ID;
                    dao.UpdateTime = DateTime.Now;
                    bool flag = false;
                    if (dao.Id == 0)
                    {
                        flag = (await _srmSortingRecord.Add(dao)) > 0;
                    }
                    else
                    {
                        flag = await _srmSortingRecord.Update(dao, null, new List<string> { "Status", "CreateUser", "CreateTime" });
                    }
                    if (flag)
                    {
                        data.success = true;
                        data.msg = "操作成功";
                        i++;
                    }
                }
            }
            return data;

        }
        /// <summary>
        /// 打印标签
        /// </summary>
        /// <param name="printDto">打印标签参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<string>> Print([FromBody] PrintDto printDto)
        {
            var data = new MessageModel<string>() { success = false };
            if (printDto == null)
            {
                data.success = false;
                data.status = 500;
                data.msg = "参数不能为空";
                return data;
            }
            if (printDto.Qty <= 0)
            {
                data.success = false;
                data.status = 500;
                data.msg = "发货数量必须大于0";
                return data;
            }
            var model = await _purchaseOrderDetail.QueryModel(t => t.fID == printDto.FID);
            if (model == null)
            {
                data.success = false;
                data.status = 500;
                data.msg = "无效的FID";
                return data;
            }
            var dao = await _srmSortingRecord.QueryModel(t => t.FID == printDto.FID);
            if (dao == null)
                dao = new SrmSortingRecordDao();
            dao.FID = printDto.FID;
            dao.Qty = printDto.Qty;
            dao.OrderId = model.OrderId;
            dao.OrderDetailId = string.IsNullOrWhiteSpace(model.SaleId) ? 0 : Convert.ToInt32(model.SaleId);
            dao.SkuCode = model.SkuCode;
            dao.SkuId = model.CategoryId.HasValue ? Convert.ToInt64(model.CategoryId) : 0;
            var list = await _purchaseOrderHeader.Query(t => t.OrderId == dao.OrderId);
            if (list.Count > 0)
            {
                dao.SupplierCode = list.FirstOrDefault().SupplierCode;
                dao.SupplierId = list.FirstOrDefault().SupplierId.Value;
            }
            dao.CustomerCode = model.CustomerCode;
            dao.Flag = 1;
            dao.PackQty = printDto.PackQty;
            dao.Price = model.Price;
            dao.UpdateUser = _user.ID;
            dao.UpdateTime = DateTime.Now;
            bool flag = false;
            if (dao.Id == 0)
            {
                dao.CreateUser = _user.ID;
                flag = (await _srmSortingRecord.Add(dao)) > 0;
            }
            else
            {
                flag = await _srmSortingRecord.Update(dao, null, new List<string> { "Status", "CreateUser", "CreateTime" });
            }
            if (flag)
            {
                data.success = true;
                data.msg = "操作成功";
            }
            return data;
        }
        /// <summary>
        /// 缺货
        /// </summary>
        /// <param name="lackGoodsDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<string>> LackGoods([FromBody] LackGoodsDto lackGoodsDto)
        {
            int fID = lackGoodsDto.FID;
            var data = new MessageModel<string>() { success = false };
            var model = await _purchaseOrderDetail.QueryModel(t => t.fID == fID);
            if (model == null)
            {
                data.success = false;
                data.status = 500;
                data.msg = "无效的FID";
                return data;
            }
            SrmSortingRecordDao dao = new SrmSortingRecordDao();
            dao.FID = fID;
            dao.Qty = 0;
            dao.Price = model.Price;
            dao.OrderId = model.OrderId;
            dao.OrderDetailId = string.IsNullOrWhiteSpace(model.SaleId) ? 0 : Convert.ToInt32(model.SaleId);
            dao.SkuCode = model.SkuCode;
            dao.SkuId = model.CategoryId.HasValue ? Convert.ToInt64(model.CategoryId) : 0;
            var list = await _purchaseOrderHeader.Query(t => t.OrderId == dao.OrderId);
            if (list.Count > 0)
            {
                dao.SupplierCode = list.FirstOrDefault().SupplierCode;
                dao.SupplierId = list.FirstOrDefault().SupplierId.Value;
            }
            dao.CustomerCode = model.CustomerCode;
            dao.Flag = 2;
            dao.PackQty = 0;
            dao.CreateUser = _user.ID;
            dao.CreateTime = DateTime.Now;
            dao.UpdateUser = _user.ID;
            dao.UpdateTime = DateTime.Now;
            bool flag = false;
            if (dao.OrderDetailId == 0)
            {
                _srmSortingRecord.DeleteByFId(fID).Wait();
            }
            else
            {
                _srmSortingRecord.DeleteBySaleId(dao.OrderDetailId, dao.SupplierCode).Wait();
            }
            dao.Status = 1;
            dao.PackNum = 0;
            flag = (await _srmSortingRecord.Add(dao)) > 0;
            if (flag)
            {
                data.success = true;
                data.msg = "操作成功";
                //var receiptRecord = new ReceiptRecord();
                //receiptRecord.BarCode = "";
                //receiptRecord.UpdateUser = _user.ID;
                //receiptRecord.FID = fID;
                //receiptRecord.ReceiptQty = 0;
                //receiptRecord.CustomerCode = dao.CustomerCode;
                //receiptRecord.SupplierCode = dao.SupplierCode;
                //receiptRecord.SkuCode = dao.SkuCode;
                //_receiptRecordServices.UpdateReceiptRecordStatus(fID).Wait();
                //await _receiptRecordServices.Add(receiptRecord);
                string upSQL = "update [供应链].[dbo].采购订单表体  set [缺货数]=辅数量 ,报货数=0,收货数=0 where fID=";
                string sql = $@"{upSQL}@fID ;  exec [系统].[dbo].[p日志记录] 'OMS.Wechat',' ','','','{_user.Namec}','供应商打码缺货,同步缺货数量','数据库','{upSQL + fID}','','{DateTime.Now}' ";
                await _purchaseOrderDetail.ExecuteCommand(sql, new { fID });
            }
            return data;
        }

        /// <summary>
        /// 按照产品查询
        /// </summary>
        /// <param name="querymodel"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<PageModel<ERPPurchaseDetailDTO>>> GetSKUGroup([FromQuery] SearchERPPurchaseDetailDTO querymodel)
        {
            querymodel.SupplierCode = (await _supplierServices.QueryById(_user.ResId))?.codec;
            List<ERPPurchaseDetailDTO> dto = new List<ERPPurchaseDetailDTO>();
            if (string.IsNullOrEmpty(querymodel.SupplierCode))
                return new MessageModel<PageModel<ERPPurchaseDetailDTO>>()
                { msg = "获取成功", success = true, response = new PageModel<ERPPurchaseDetailDTO>() { data = dto } };

            var list = await _purchaseOrderDetail.GetERPSuppPurchase(querymodel);
            if (list.Count > 0)
            {
                var fids = list.Select(i => i.fID).ToArray();
                var records = await _srmSortingRecord.Query(i => fids.Contains(i.FID) && i.Status == 1);
                dto = list.GroupBy(i => new { i.SkuCode, i.SkuName, i.PurchasePrice, i.PurchaseUnit }).Select(i => new ERPPurchaseDetailDTO
                           ()
                { SkuCode = i.Key.SkuCode, SkuName = i.Key.SkuName, PurchasePrice = i.Key.PurchasePrice, PurchaseUnit = i.Key.PurchaseUnit, Qty = i.Sum(c => c.PurchaseQty), Flag = (i.Any(f => !records.Any(r => r.FID == f.fID)) ? 0 : 1), AnswerAmt = i.Sum(c => records.Where(r => r.FID == c.fID).Sum(r => r.Price * r.Qty)) }).OrderBy(i => i.Flag).ToList();

                //data.data.ForEach(i => { });.ThenBy(i => i.SkuCode)
            }
            return new MessageModel<PageModel<ERPPurchaseDetailDTO>>()
            { msg = "获取成功", success = true, response = new PageModel<ERPPurchaseDetailDTO>() { data = dto } };
        }


        /// <summary>
        /// 按照客户排序
        /// </summary>
        /// <param name="querymodel"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<PageModel<ERPPurchaseDetailDTO>>> GetCustoemrGroup([FromQuery] SearchERPPurchaseDetailDTO querymodel)
        {
            querymodel.SupplierCode = (await _supplierServices.QueryById(_user.ResId))?.codec;
            List<ERPPurchaseDetailDTO> dto = new List<ERPPurchaseDetailDTO>();

            if (string.IsNullOrEmpty(querymodel.SupplierCode))
                return new MessageModel<PageModel<ERPPurchaseDetailDTO>>()
                { msg = "获取成功", success = true, response = new PageModel<ERPPurchaseDetailDTO>() { data = dto } };

            var list = await _purchaseOrderDetail.GetERPSuppPurchase(querymodel);
            if (list.Count > 0)
            {
                var fids = list.Select(i => i.fID).ToArray();
                var records = await _srmSortingRecord.Query(i => fids.Contains(i.FID) && i.Status == 1);
                dto = list.GroupBy(i => new { i.CustomerId, i.CustomerCode }).Select(i => new ERPPurchaseDetailDTO()
                { CustomerId = i.Key.CustomerId, CustomerCode = i.Key.CustomerCode, Qty = i.Count(), Flag = (i.Any(f => !records.Any(r => r.FID == f.fID)) ? 0 : 1), AnswerAmt = i.Sum(c => records.Where(r => r.FID == c.fID).Sum(r => r.Price * r.Qty)), CustomerPriority = i.FirstOrDefault().CustomerPriority }).OrderBy(i => i.Flag).ToList();//ThenByDescending(i => i.CustomerPriority).ThenBy(i => i.CustomerId)Flag = (i.Any(f => f.Flag == 0) ? 0 : 1), 

            }
            return new MessageModel<PageModel<ERPPurchaseDetailDTO>>()
            { msg = "获取成功", success = true, response = new PageModel<ERPPurchaseDetailDTO>() { data = dto } };
        }

        /// <summary>
        /// 自采供应商查询
        /// </summary>
        /// <param name="querymodel"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<PageModel<ERPPurchaseDetailDTO>>> GetSuppGroup([FromQuery] SearchERPPurchaseDetailDTO querymodel)
        {
            //querymodel.SupplierCode = (await _supplierServices.QueryById(_user.ResId))?.codec;
            if (_user.ResId == 1) querymodel.SupplierMarket = "御桥";
            if (_user.ResId == 2) querymodel.SupplierMarket = "江阳";
            //querymodel.SupplierMarket = "御桥";

            List<ERPPurchaseDetailDTO> dto = new List<ERPPurchaseDetailDTO>();
            var list = await _purchaseOrderDetail.GetERPSuppPurchase(querymodel);
            if (list.Count > 0)
            {
                var fids = list.Select(i => i.fID).ToArray();
                var records = await _srmSortingRecord.Query(i => fids.Contains(i.FID) && i.Status == 1);

                dto = list.GroupBy(i => new { i.SupplierCode, i.SupplierName }).Select(i => new ERPPurchaseDetailDTO()
                {
                    SupplierCode = i.Key.SupplierCode,
                    SupplierName = i.Key.SupplierName,
                    PinYin = NPinyinHelper.GetSpellCode(i.Key.SupplierName),
                    Qty = i.Count()
                ,
                    Flag = (i.Any(f => !records.Any(r => r.FID == f.fID)) ? 0 : 1),
                    AnswerAmt = i.Sum(c => records.Where(r => r.FID == c.fID).Sum(r => r.Price * r.Qty))
                }).OrderBy(i => i.Flag).OrderBy(i => i.PinYin).ToList();
                //data.data.ForEach(i => { });, CustomerPriority = i.FirstOrDefault().CustomerPriority //(records.Any(r=>r.Flag==0&& i.Any(f => f.SupplierCode == r.SupplierCode) ) ? 0 : 1), 
            }
            return new MessageModel<PageModel<ERPPurchaseDetailDTO>>()
            { msg = "获取成功", success = true, response = new PageModel<ERPPurchaseDetailDTO>() { data = dto } };
        }

        /// <summary>
        /// 根据产品或者客户获取明细
        /// </summary>
        /// <param name="querymodel"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<PageModel<ERPPurchaseDetailDTO>>> GetDetail([FromQuery] SearchERPPurchaseDetailDTO querymodel)
        {
            if (string.IsNullOrEmpty(querymodel.SupplierCode))
                querymodel.SupplierCode = (await _supplierServices.QueryById(_user.ResId))?.codec;
            var list = await _purchaseOrderDetail.GetERPSuppPurchase(querymodel);
            List<ERPPurchaseDetailDTO> dto = new List<ERPPurchaseDetailDTO>();
            dto = _mapper.Map<List<ERPPurchaseDetailDTO>>(list);
            if (dto.Count() > 0)
            {
                var fids = dto.Select(i => i.fID).ToArray();
                var records = await _srmSortingRecord.Query(i => fids.Contains(i.FID) && i.Status == 1);
                dto.ForEach(i => { i.Flag = (records.Any(r => r.FID == i.fID && r.Flag == 2) ? 2 : (records.Any(r => r.FID == i.fID) ? 1 : 0)); i.Qtys = records.Where(r => r.FID == i.fID).Select(r => r.Qty).ToList(); });
                //dto.OrderBy(i => i.Flag).ThenByDescending(i => i.CustomerPriority).ThenBy(i => i.CustomerId).ThenBy(i => i.SkuCode).ToList();
                dto.OrderBy(i => i.Flag).ToList();
                //if (!string.IsNullOrEmpty(querymodel.SkuCode) || !string.IsNullOrEmpty(querymodel.CustomerCode))
            }

            return new MessageModel<PageModel<ERPPurchaseDetailDTO>>()
            { msg = "获取成功", success = true, response = new PageModel<ERPPurchaseDetailDTO>() { data = dto } };
        }
    }
}